package cn.funnymap.lgis.tools.vector.generator.wkt;

import cn.funnymap.lgis.tools.exception.ShpGeneratorValidationException;
import cn.funnymap.lgis.tools.vector.generator.GeneratorContent;
import cn.funnymap.lgis.tools.vector.generator.ShpGenerator;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * WKT-Shapefile生成器
 *
 * @author jiaoxn
 */
public abstract class Wkt2ShpGenerator extends ShpGenerator {
    private final Wkt2ShpGeneratorParam generatorParam;

    protected Wkt2ShpGenerator(Path shpFilePath,
                               Wkt2ShpGeneratorParam generatorParam) {
        super(shpFilePath);
        this.generatorParam = generatorParam;
    }

    @Override
    protected GeneratorContent buildGeneratorContent() {
        try {
            List<String> wktList = this.generatorParam.getWktList();
            List<HashMap<String, Object>> values = this.generatorParam.getAttrValueList();
            List<Geometry> geometryList = this.wkt2GeometryList(wktList);
            CoordinateReferenceSystem crs = this.generatorParam.getCrs();

            return new GeneratorContent(geometryList, generatorParam.getFieldList(), values, crs);
        } catch (ParseException exception) {
            throw new ShpGeneratorValidationException("WKT格式校验失败，请检查输入参数");
        }
    }
    private List<Geometry> wkt2GeometryList(List<String> wktList) throws ParseException {
        List<Geometry> geometryList = new ArrayList<>();

        for (String wkt : wktList) {
            Geometry geometry = this.wkt2geometry(wkt);
            geometryList.add(geometry);
        }

        return geometryList;
    }
    private Geometry wkt2geometry(String wkt) throws ParseException {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
        WKTReader reader = new WKTReader(geometryFactory);
        return reader.read(wkt);
    }
}
